//获取小说接口
'use strict';
let uniId = require('uni-id')
let db = uniCloud.database()
let dbCommad = db.command
exports.main = async (event, context) => {
	//处理url化的post接口
	if(event.body){
		let ip =event.headers['x-real-ip']
		event={
			...JSON.parse(event.body)
		},
		//这里需要手动传入context参数
		uniId = uniId.createInstance({ // 创建uni-id实例，其上方法同uniID
		    context:{
				PLATFORM:'app-plus',
				APPID:'__UNI__B10F710',
				LOCALE:'zh-Hans',
				CLIENTIP:ip
			}, // 传入context防止不同请求互相影响
		})
	}
	
	// 校验token
	let result = await payloadToken(event)
	if (result.code != 0) { //校验不成功【如果校验成功返回uid】
		return result
	}

	let res = {}
	//查询分类
	if (event.active == 'classification') {
		let bookType = await getClassificationFn()
		res = {
			code: 0,
			data: bookType
		}
	}
	//搜索小说
	if (event.active == 'seachBook') {
		let booklist = await getSeachBook(event)
		res = {
			code: 0,
			data: booklist.data,
			total: booklist.total,
			page: {
				pageSize: event.params.pageSize,
				pageNum: event.params.pageNum
			}
		}
	}
	//获取小说详情
	if (event.active == 'getBookInfo') {
		res = await getBookInfo(event)
	}
	//获取小说目录
	if (event.active == 'getBookMenu') {
		res = await getBookMenu(event)
	}
	//获取小说同类推荐
	if (event.active == 'similar') {
		res = await getBookInfoSimilar(event)
	}
	//增加书的人气值
	if (event.active == 'addBookPopularity') {
		res = await addBookPopularity(event)
	}
	//获取小说人气飙升榜
	if (event.active == 'getPopularityList') {
		res = await getPopularityList(event)
	}
	//获取小说排行榜
	if (event.active == 'getRankingList') {
		res = await getrankingList(event)
	}
	//获取小说精选菜单
	if(event.active == 'selectedCategories'){
		res = await selectedCategories()
	}
	//获取小说男频菜单
	if(event.active == 'maleFrequencyMenu'){
		res = await maleFrequencyMenu()
	}
	//获取小说女频菜单
	if(event.active == 'womanFrequencyMenu'){
		res = await womanFrequencyMenu()
	}
	//获取小说排行菜单
	if(event.active == 'getSeniorityMenu'){
		res = await getSeniorityMenu()
	}
	//最热榜
	if(event.active=='getHotList'){
		res = await getHotList(event)
	}
	//推荐榜
	if(event.active=='getRecommendationList'){
		res = await getRecommendationList(event)
	}
	//周榜
	if(event.active=='getWeekList'){
		res = await getWeekList(event)
	}
	//月榜
	if(event.active=='getMonthList'){
		res = await getMonthList(event)
	}
	
	// 返回数据给客户端
	return res
};
//获取小说排行菜单
async function getSeniorityMenu(){
	let result = {}
	let params={
		pageSize:10,
		pageNum:1
	}
	//获取周榜
	result.weekList = (await getWeekList({params})).data
	//获取月榜
	result.monthList = (await getMonthList({params})).data
	return {
		code: 0,
		data: result,
		msg: '成功'
	}
}
//获取月榜
async function getMonthList(event){
	let result = await db.collection('bookList').orderBy('monthClick', 'desc').skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return {
		code: 0,
		data: result.data,
		msg: '成功'
	}
}
//获取周榜
async function getWeekList(event){
	let result = await db.collection('bookList').orderBy('weeklyClick', 'desc').skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return {
		code: 0,
		data: result.data,
		msg: '成功'
	}
}
//获取小说女频菜单
async function womanFrequencyMenu(){
	let result = {}
	let params={
		type:2,//1为男生2为女生
		pageSize:10,
		pageNum:1
	}
	//获取推荐榜
	result.recommendationList = (await getRecommendationList({params})).data
	//获取字数榜
	result.wordList = await getWordList({params})
	return {
		code: 0,
		data: result,
		msg: '成功'
	}
}
//获取小说男频菜单
async function maleFrequencyMenu(){
	let result = {}
	let params={
		type:1,//1为男生2为女生
		pageSize:10,
		pageNum:1
	}
	//获取男生推荐榜
	result.recommendationList = (await getRecommendationList({params})).data
	//获取男生字数榜
	result.wordList = await getWordList({params})
	return {
		code: 0,
		data: result,
		msg: '成功'
	}
}
//获取字数榜
async function getWordList(event){
	//type1为男生2为女生
	let type= event.params.type
	let arr=[]
	switch(type){
		case 1: //男生推荐榜，玄幻，修真，科幻
			arr=[1,2,6]
			break;
		case 2: //女人推荐榜，都市、穿越、网页
			arr=[3,4,5]
			break;
		default:
			arr=[]
	}	
	let result = await db.collection('bookList').orderBy('allTotal', 'desc').where({
			bookType:dbCommad.in(arr)
		}).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return result.data
}
//获取推荐榜
async function getRecommendationList(event){
	//type1为男生2为女生
	let type= event.params.type
	let arr=[]
	switch(type){
		case 1: //男生推荐榜，玄幻，修真，科幻
			arr=[1,2,6]
			break;
		case 2: //女人推荐榜，都市、穿越、网页
			arr=[3,4,5]
			break;
		default:
			arr=[1,2,3,4,5,6]
	}	
	let result = await db.collection('bookList').orderBy('allRecommend', 'desc').where({
			bookType:dbCommad.in(arr)
		}).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return {
		code: 0,
		data: result.data,
		msg: '成功'
	}
}
//获取小说精选菜单
async function selectedCategories(){
	let result = {}
	let params={
		pageSize:10,
		pageNum:1
	}
	//获取全网大热榜
	result.hotList = (await getHotList({params})).data
	//获取超人气精品
	result.popularList = await getPopularList({params})
	//获取猜你喜欢
	result.likeList = (await getLikeList({params})).data
	return {
		code: 0,
		data: result,
		msg: '成功'
	}
}
//获取超人气精品
async function getPopularList(event){
	let result = await db.collection('bookList').orderBy('popularityNum', 'desc').skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return result.data
}
//获取全网大热榜
async function getHotList(event){
	let result = await db.collection('bookList').orderBy('allClick', 'desc').skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
	return {
		code: 0,
		data: result.data,
		msg: '成功'
	}
}

//获取小说排行榜
async function getrankingList(event){
	let result = {}
	if (event.params&&event.params.type) {
		let type= event.params.type
		let arr=[]
		switch(type){
			case 1: //男生人气排行榜，玄幻，修真，科幻
				arr=[1,2,6]
				break;
			case 2: //女人气排行榜，都市、穿越、网页
				arr=[3,4,5]
				break;
			default:
				arr=[]
		}	
		let data = await db.collection('bookList').orderBy('popularityNum', 'desc').where({
			bookType:dbCommad.in(arr)
		}).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
		result = {
			code: 0,
			data: data.data,
			msg: '成功'
		}
	} else {
		result = {
			code: 400,
			msg: '参数错误'
		}
	}
	return result
}

//获取小说人气飙升榜
async function getPopularityList(event) {
	//orderBy对结果进行降序排序
	let data = await db.collection('bookList').orderBy('popularityNum', 'desc').field({
			chapter:false //当前字段不返回【是否返回章节默认false不返回】
		}).limit(10).get()
	return {
		code:0,
		data:{
			...data,
			title:'人气飙升榜'
		},
		msg:'成功'
	}
}
//给书增加人气值
async function addBookPopularity(event) {
	let data = await db.collection('bookList').doc(event.params.bookId).update({
		popularityNum: dbCommad.inc(1)
	})
	return {
		code: 0,
		data: data,
		msg: '成功'
	}
}
//获取猜你喜欢随机取10个
async function getLikeList(event) {
	//随机取出三条记录
	let data = await db.collection('bookList').aggregate()
	.sample({
		size: 10 //随机取出10条记录
	}).end()
	return {
		code: 0,
		data: data.data,
		msg: '成功'
	}
}

//获取小说同类推荐
async function getBookInfoSimilar(event) {
	let result = {}
	if (result) {
		console.log('获取小说同类推荐',event.params.bookType);
		//随机取出三条记录
		let data = await db.collection('bookList').aggregate()
		.match({
			bookType: event.params.bookType||'' //查询的条件【玄幻，都市...】
		})
		.sample({
			size: 3 //随机取出3条记录
		}).end()
		console.log('获取小说同类推荐',data);
		result = {
			code: 0,
			data: data.data,
			msg: '成功'
		}
	} else {
		result = {
			code: 0,
			data: [],
			msg: '暂无同类小说'
		}
	}
	return result
}

//获取小说详情
async function getBookInfo(event) {
	let result = {}
	if (event.params.bookId) {
		let data = await db.collection('bookList').doc(event.params.bookId).get()
		result = {
			code: 0,
			data: data.data,
			msg: '成功'
		}
	} else {
		result = {
			code: 400,
			msg: '暂无此书'
		}
	}
	return result
}
//获取小说章节目录
async function getBookMenu(event) {
	let result = {}
	if (event.params.bookId) {
		let data = await db.collection('bookMenu').doc(event.params.bookId).get()
		result = {
			code: 0,
			data: data.data,
			msg: '成功'
		}
	} else {
		result = {
			code: 400,
			msg: '暂无此书'
		}
	}
	return result
}


//搜索小说
async function getSeachBook(event) {
	let result = {}
	
	if (event.params.bookType) {//分类查询
		// bookName:db.RegExp({ // 此方式阿里云不支持模糊查询
		// 	regexp: event.params.keyword, //从搜索栏中获取的value作为规则进行匹配。
		// 	options: 'i', //大小写不区分
		// }),
		let req={
			bookName:new RegExp(event.params.keyword,'i'),//阿里云模糊查询
			bookType:event.params.bookType
		}
		result.data = (await db.collection('bookList').where(req).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).orderBy("_id", "desc").get()).data
		//获取总条数
		result.total = (await db.collection('bookList').where(req).count()).total
	} else {//全部查询
		let req={
			bookName:new RegExp(event.params.keyword,'i'),//阿里云模糊查询
		}
		//集合查询
		result.data = (await db.collection('bookList').where(req).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).orderBy("_id", "desc").get()).data
		result.total = (await db.collection('bookList').where(req).count()).total
	}
	return result

}

//校验token
async function payloadToken(event) {
	//校验token
	let payload = {}
	//用户带的参数
	let params = event.params || {}
	if (!event.token) {
		return {
			code: 403,
			msg: '用户未登录或登录失效'
		}
	}
	//校验token
	payload = await uniId.checkToken(event.token);
	//校验失败
	if (payload.code && payload.code > 0) {
		return payload
	}
	params.uid = payload.uid //校验成功之后会返回用户Id
	return {
		code: 0,
		...params
	}
}

//查询小说分类
async function getClassificationFn() {
	//1为玄幻，2修真，3都市，4穿越，5网游，6科幻，7其他
	let xuanhuan = await db.collection('bookList').where({
		bookType: 1 //玄幻
	}).count()
	let dushi = await db.collection('bookList').where({
		bookType: 2 //修真
	}).count()
	let xianxia = await db.collection('bookList').where({
		bookType: 3 //都市
	}).count()
	let lishi = await db.collection('bookList').where({
		bookType: 4 //穿越
	}).count()
	let kehuan = await db.collection('bookList').where({
		bookType: 5 //网游
	}).count()
	let yanqing = await db.collection('bookList').where({
		bookType: 6 //科幻
	}).count()
	let wangyou = await db.collection('bookList').where({
		bookType: 7 //其他
	}).count()
	let jingji = await db.collection('bookList').where({
		bookType: 8 //暂无
	}).count()
	let arr = {
		male: [{ //男生的
			name: '玄幻',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/4f493c20-3ac5-11eb-8ff1-d5dcf8779628.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/5021e8e0-3ac5-11eb-8ff1-d5dcf8779628.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/5140ed70-3ac5-11eb-97b7-0dc4655d6e68.jpg'
			],
			bookType: 1,
			total: xuanhuan.total
		}, {
			name: '修真',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/51df5050-3ac5-11eb-8a36-ebb87efcf8c0.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/528c0b10-3ac5-11eb-8a36-ebb87efcf8c0.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/533d0b90-3ac5-11eb-bc56-c9cea619f663.jpg'
			],
			bookType: 2,
			total: dushi.total
		}, {
			name: '都市',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/4d137060-3ac5-11eb-8ff1-d5dcf8779628.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/4dca3d40-3ac5-11eb-8a36-ebb87efcf8c0.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/4e97ed80-3ac5-11eb-b997-9918a5dda011.jpg'
			],
			bookType: 3,
			total: xianxia.total
		}, {
			name: '穿越',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/55f01da0-3ac5-11eb-bd01-97bc1429a9ff.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/56925110-3ac5-11eb-8a36-ebb87efcf8c0.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/4c5acec0-3ac5-11eb-97b7-0dc4655d6e68.jpg'
			],
			bookType: 4,
			total: lishi.total
		}, {
			name: '网游',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/53efe0d0-3ac5-11eb-b680-7980c8a877b8.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/549b6310-3ac5-11eb-bd01-97bc1429a9ff.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/553977d0-3ac5-11eb-8a36-ebb87efcf8c0.jpg'
			],
			bookType: 5,
			total: kehuan.total
		}],
		female:[{//女生的
			name: '科幻',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8b5a6a90-4f3d-11eb-97b7-0dc4655d6e68.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/88701be0-4f3d-11eb-8a36-ebb87efcf8c0.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8aa2b350-4f3d-11eb-bd01-97bc1429a9ff.jpg'
			],
			bookType: 6,
			total: yanqing.total
		},
		{
			name: '其他',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8939ad70-4f3d-11eb-bd01-97bc1429a9ff.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/89ead500-4f3d-11eb-b997-9918a5dda011.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8cbdf230-4f3d-11eb-bd01-97bc1429a9ff.jpg'
			],
			bookType: 7,
			total: wangyou.total
		},
		{
			name: '竞技',
			image: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8d8cb3e0-4f3d-11eb-bd01-97bc1429a9ff.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/8c094830-4f3d-11eb-bd01-97bc1429a9ff.jpg',
				'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-lz001/5140ed70-3ac5-11eb-97b7-0dc4655d6e68.jpg'
			],
			bookType: 8,
			total: jingji.total
		}
		]
	}
	return arr
}
